package com.aaa.boot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author MK
 * @version 1.0
 * 创建时间：2025/3/27 11:03
 */

//@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(
                new HandlerInterceptor() {
                    /**
                     * 拦截器前置处理方法，用于验证用户登录状态
                     *
                     * @param request  HTTP请求对象，用于获取会话信息
                     * @param response HTTP响应对象，用于返回未登录提示
                     * @param handler  被拦截的请求处理对象
                     * @return boolean 是否放行请求：
                     *         true-继续执行后续处理链，false-终止请求处理
                     * @throws Exception 可能抛出的IO异常
                     */
                    @Override
                    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                        String method = request.getMethod();
                        if (method.equals("OPTIONS")){
                            return true;
                        }
                        // 从会话中获取员工登录信息
                        Object emp = request.getSession().getAttribute("emp");

                        // 未登录处理逻辑
//                        if(emp == null){
//                            // 设置JSON格式响应
//                            response.setContentType("text/json;charset=utf-8");
//                            PrintWriter out = response.getWriter();
//                            // 返回未登录提示信息
//                            out.write("{'msg':'sorry must login'}");
//
//                            return true;
//                        }
                        return true;
                    }

                }
        ).order(1).addPathPatterns("/**").excludePathPatterns("/emp/login")
                .excludePathPatterns("/doc.html","webjars/**","swagger-resources/**","/v2/api-docs")
                .excludePathPatterns("/*.jpg","/*.jpeg","/*.png","/*.gif","/*.css","/*.js","/*.html","/*.ico")
                .excludePathPatterns("/upload/uploadHeadImg");
    }
}
